<template>
  <div class="training-budget">
    <h2>年度培训费用预算表</h2>
    <div class="operation-buttons">
      <el-button icon="el-icon-back" @click="handleBack()">返回</el-button>
      <el-button type="success" icon="el-icon-menu" @click="goToList">预算列表</el-button>
      <el-button type="primary" icon="el-icon-search" @click="showSearchDialog">查询</el-button>
    </div>
    
    <!-- 查询对话框 -->
    <el-dialog title="查询预算" :visible.sync="searchDialogVisible" width="50%">
      <el-form :model="searchForm" label-width="100px">
        <el-form-item label="申报部门">
          <el-input v-model="searchForm.department" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="年度">
          <el-date-picker
            v-model="searchForm.year"
            type="year"
            placeholder="选择年份"
            value-format="yyyy"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="searchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="searchBudgets">查询</el-button>
      </div>
    </el-dialog>

    <!-- 查询结果表格 -->
    <el-dialog title="查询结果" :visible.sync="resultDialogVisible" width="80%">
      <el-table :data="searchResults" style="width: 100%">
        <el-table-column prop="department" label="申报部门"></el-table-column>
        <el-table-column prop="year" label="年度"></el-table-column>
        <el-table-column prop="date" label="申报日期"></el-table-column>
        <el-table-column prop="totalAmount" label="总金额">
          <template slot-scope="scope">
            {{ scope.row.totalAmount.toFixed(2) }} 元
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="制订人"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="text" @click="viewBudget(scope.row)">查看</el-button>
            <el-button type="text" @click="editBudget(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <div class="content">
      <el-form :model="formData" ref="formData" :rules="rules" label-width="100px">
        <!-- 表单头部信息 -->
        <div class="form-header">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="申报部门" prop="department">
                <el-input v-model="formData.department" placeholder="请输入部门名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="年度" prop="year">
                <el-date-picker
                  v-model="formData.year"
                  type="year"
                  placeholder="选择年份"
                  value-format="yyyy"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申报日期" prop="date">
                <el-date-picker
                  v-model="formData.date"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 表格内容 -->
        <el-table
          :data="tableData"
          border
          class="budget-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
          <el-table-column prop="trainingCategory" label="培训类别" min-width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.trainingCategory" placeholder="请输入培训类别"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="trainingProgram" label="培训课程/方案" min-width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.trainingProgram" placeholder="请输入培训课程"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="trainingPeople" label="培训预到人数" min-width="120">
            <template slot-scope="scope">
              <el-input 
                v-model.number="scope.row.trainingPeople"
                @input="validateNumber($event, scope.row, 'trainingPeople')"
                placeholder="请输入人数">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="actualPeople" label="实训预算人数" min-width="120">
            <template slot-scope="scope">
              <el-input 
                v-model.number="scope.row.actualPeople"
                @input="validateNumber($event, scope.row, 'actualPeople')"
                placeholder="请输入人数">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="applicationFee" label="申请课程费用" min-width="120">
            <template slot-scope="scope">
              <el-input 
                v-model.number="scope.row.applicationFee"
                @input="validateNumber($event, scope.row, 'applicationFee')"
                placeholder="请输入费用">
                <template slot="append">元</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="materialFee"
            label="课件资料费用"
            min-width="120">
            <template slot-scope="scope">
              <el-input 
                v-model.number="scope.row.materialFee"
                @input="validateNumber($event, scope.row, 'materialFee')"
                placeholder="请输入费用">
                <template slot="append">元</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="subsidyFee"
            label="实训补助费用"
            min-width="120">
            <template slot-scope="scope">
              <el-input 
                v-model.number="scope.row.subsidyFee"
                @input="validateNumber($event, scope.row, 'subsidyFee')"
                placeholder="请输入费用">
                <template slot="append">元</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="externalFee"
            label="外训费用"
            min-width="120">
            <template slot-scope="scope">
              <el-input 
                v-model.number="scope.row.externalFee"
                @input="validateNumber($event, scope.row, 'externalFee')"
                placeholder="请输入费用">
                <template slot="append">元</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="otherFee"
            label="其他费用备注"
            min-width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.otherFee"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="subtotal" label="费用小计" min-width="120">
            <template slot-scope="scope">
              <div class="subtotal">{{ calculateSubtotal(scope.row).toFixed(2) }} 元</div>
            </template>
          </el-table-column>
          <el-table-column prop="personnelFee" label="人均费用" min-width="120">
            <template slot-scope="scope">
              <div class="per-fee">{{ calculatePerPersonFee(scope.row) }} 元</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template slot-scope="scope">
              <el-button 
                type="text" 
                icon="el-icon-delete" 
                @click="removeRow(scope.$index)"
                class="delete-btn">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 表格底部合计 -->
        <div class="table-footer">
          <el-button type="text" icon="el-icon-plus" @click="addRow">添加行</el-button>
          <span class="total-amount">合计金额：{{ total.toFixed(2) }} 元</span>
        </div>

        <!-- 审批信息 -->
        <div class="approval-info">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="批准" prop="approver">
                <el-input v-model="formData.approver" placeholder="请输入审批人"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="会签审核" prop="reviewer">
                <el-input v-model="formData.reviewer" placeholder="请输入审核人"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="信息汇总" prop="collector">
                <el-input v-model="formData.collector" placeholder="请输入汇总人"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="制订" prop="creator">
                <el-input v-model="formData.creator" placeholder="请输入制订人"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" icon="el-icon-check" @click="saveForm('formData')">保存</el-button>
          <el-button icon="el-icon-refresh-left" @click="resetForm('formData')">重置</el-button>
        </div>
      </el-form>
    </div>

    <!-- 添加预算列表对话框 -->
    <el-dialog title="预算列表" :visible.sync="listDialogVisible" width="80%">
      <div class="filter-section">
        <el-input
          v-model="searchQuery"
          placeholder="请输入培训项目名称"
          style="width: 200px"
          clearable
          @keyup.enter.native="handleSearch">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="handleSearch">
        </el-date-picker>
      </div>

      <el-table :data="budgetList" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="projectName" label="培训项目" min-width="150"></el-table-column>
        <el-table-column prop="department" label="申请部门" width="120"></el-table-column>
        <el-table-column prop="trainingType" label="培训类型" width="120"></el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120"></el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120"></el-table-column>
        <el-table-column prop="totalBudget" label="预算总额" width="120" align="right">
          <template slot-scope="scope">
            {{ scope.row.totalBudget }}元
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'TrainingBudget',
  data() {
    return {
      formData: {
        department: '',
        year: '',
        date: '',
        approver: '',
        reviewer: '',
        collector: '',
        creator: ''
      },
      rules: {
        department: [{ required: true, message: '请输入申报部门', trigger: 'blur' }],
        year: [{ required: true, message: '请选择年度', trigger: 'change' }],
        date: [{ required: true, message: '请选择申报日期', trigger: 'change' }],
        approver: [{ required: true, message: '请输入审批人', trigger: 'blur' }],
        reviewer: [{ required: true, message: '请输入审核人', trigger: 'blur' }],
        collector: [{ required: true, message: '请输入汇总人', trigger: 'blur' }],
        creator: [{ required: true, message: '请输入制订人', trigger: 'blur' }]
      },
      tableData: [this.getEmptyRow()],
      searchDialogVisible: false,
      resultDialogVisible: false,
      searchForm: {
        department: '',
        year: ''
      },
      searchResults: [],
      currentBudgetId: null,
      listDialogVisible: false,
      searchQuery: '',
      dateRange: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      budgetList: [
        {
          projectName: '新员工入职培训',
          department: '人力资源部',
          trainingType: '内部培训',
          startDate: '2024-03-01',
          endDate: '2024-03-15',
          totalBudget: 5000,
          status: '已审批'
        },
        {
          projectName: '管理技能提升培训',
          department: '运营部',
          trainingType: '外部培训',
          startDate: '2024-04-01',
          endDate: '2024-04-10',
          totalBudget: 8000,
          status: '待审批'
        },
        {
          projectName: '技术人员专业培训',
          department: '技术部',
          trainingType: '内部培训',
          startDate: '2024-05-15',
          endDate: '2024-05-20',
          totalBudget: 6000,
          status: '已审批'
        }
      ]
    }
  },
  computed: {
    total() {
      return this.tableData.reduce((sum, row) => {
        const subtotal = this.calculateSubtotal(row)
        return sum + (isNaN(subtotal) ? 0 : subtotal)
      }, 0)
    }
  },
  methods: {
    getEmptyRow() {
      return {
        trainingCategory: '',
        trainingProgram: '',
        trainingPeople: '',
        actualPeople: '',
        applicationFee: '0',
        materialFee: '0',
        subsidyFee: '0',
        externalFee: '0',
        otherFee: '',
        subtotal: 0,
        personnelFee: 0
      }
    },
    validateNumber(value, row, field) {
      if (value === '') {
        row[field] = ''
        return
      }
      const num = Number(value)
      if (isNaN(num)) {
        row[field] = ''
        this.$message.warning('请输入有效的数字')
        return
      }
      if (field.includes('People') && !Number.isInteger(num)) {
        row[field] = Math.floor(num)
        this.$message.warning('人数必须为整数')
        return
      }
      if (num < 0) {
        row[field] = 0
        this.$message.warning('数值不能为负数')
        return
      }
      row[field] = num
    },
    handleBack() {
      // 返回上一页
      this.$router.back()
    },
    calculateSubtotal(row) {
      const applicationFee = Number(row.applicationFee) || 0
      const materialFee = Number(row.materialFee) || 0
      const subsidyFee = Number(row.subsidyFee) || 0
      const externalFee = Number(row.externalFee) || 0
      const otherFee = Number(row.otherFee) || 0
      return applicationFee + materialFee + subsidyFee + externalFee + otherFee
    },
    calculatePerPersonFee(row) {
      const subtotal = this.calculateSubtotal(row)
      const actualPeople = Number(row.actualPeople) || 0
      return actualPeople > 0 ? (subtotal / actualPeople).toFixed(2) : '0.00'
    },
    addRow() {
      this.tableData.push(this.getEmptyRow())
    },
    removeRow(index) {
      this.tableData.splice(index, 1)
    },
    async saveForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const budget = {
              id: this.currentBudgetId,
              ...this.formData,
              totalAmount: this.total,
              details: this.tableData.map(row => ({
                trainingCategory: row.trainingCategory,
                trainingProgram: row.trainingProgram,
                trainingPeople: Number(row.trainingPeople),
                actualPeople: Number(row.actualPeople),
                applicationFee: Number(row.applicationFee),
                materialFee: Number(row.materialFee),
                subsidyFee: Number(row.subsidyFee),
                externalFee: Number(row.externalFee),
                otherFee: row.otherFee
              }))
            }

            const response = await axios.post(
              'http://192.168.110.22:8085/new/training-budget/save',
              budget
            )

            if (response.data === "保存成功") {
              this.$message.success('保存成功')
              this.$router.push('/training-management')
            } else {
              this.$message.error('保存失败')
            }
          } catch (error) {
            console.error('保存失败', error)
            this.$message.error('保存失败：' + (error.response?.data || '服务器错误'))
          }
        } else {
          this.$message.error('请填写完整信息')
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.tableData = [this.getEmptyRow()]
    },
    showSearchDialog() {
      this.searchDialogVisible = true
    },
    async searchBudgets() {
      try {
        const response = await axios.get('http://192.168.110.22:8085/new/training-budget/list', {
          params: this.searchForm
        })
        this.searchResults = response.data
        this.searchDialogVisible = false
        this.resultDialogVisible = true
      } catch (error) {
        console.error('查询失败', error)
        this.$message.error('查询失败：' + (error.response?.data || '服务器错误'))
      }
    },
    async viewBudget(budget) {
      try {
        const response = await axios.get(
          `http://192.168.110.22:8085/new/training-budget/${budget.id}`
        )
        this.formData = {
          department: response.data.department,
          year: response.data.year,
          date: response.data.date,
          approver: response.data.approver,
          reviewer: response.data.reviewer,
          collector: response.data.collector,
          creator: response.data.creator
        }
        this.tableData = response.data.details.map(detail => ({
          trainingCategory: detail.trainingCategory,
          trainingProgram: detail.trainingProgram,
          trainingPeople: detail.trainingPeople,
          actualPeople: detail.actualPeople,
          applicationFee: detail.applicationFee,
          materialFee: detail.materialFee,
          subsidyFee: detail.subsidyFee,
          externalFee: detail.externalFee,
          otherFee: detail.otherFee
        }))
        this.currentBudgetId = budget.id
        this.resultDialogVisible = false
      } catch (error) {
        console.error('获取详情失败', error)
        this.$message.error('获取详情失败：' + (error.response?.data || '服务器错误'))
      }
    },
    editBudget(budget) {
      this.viewBudget(budget)
    },
    goToList() {
      this.listDialogVisible = true
      this.loadBudgetList()
    },
    handleSearch() {
      this.currentPage = 1
      this.loadBudgetList()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadBudgetList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadBudgetList()
    },
    loadBudgetList() {
      // 如果有搜索条件，进行过滤
      let filteredList = [...this.budgetList]
      
      if (this.searchQuery) {
        filteredList = filteredList.filter(item => 
          item.projectName.includes(this.searchQuery) ||
          item.department.includes(this.searchQuery)
        )
      }

      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0])
        const endDate = new Date(this.dateRange[1])
        filteredList = filteredList.filter(item => {
          const itemDate = new Date(item.startDate)
          return itemDate >= startDate && itemDate <= endDate
        })
      }

      // 更新总数和分页
      this.total = filteredList.length
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.budgetList = filteredList.slice(start, end)
    },
    getStatusType(status) {
      const map = {
        '待审批': 'warning',
        '已审批': 'success',
        '已驳回': 'danger'
      }
      return map[status] || 'info'
    },
    handleEdit(row) {
      // TODO: 实现编辑功能
      console.log('编辑', row)
    },
    handleDelete(row) {
      this.$confirm('确认删除该预算记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用删除API
        this.$message.success('删除成功')
        this.loadBudgetList()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.training-budget {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #f5f7fa;
}

.content {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
  font-weight: 600;
}

.budget-table {
  margin: 20px 0;
  border: 1px solid #ebeef5;
}

.budget-table ::v-deep .el-input__inner {
  text-align: center;
}

.budget-table ::v-deep .el-input-group__append {
  padding: 0 10px;
}

.subtotal, .per-fee {
  text-align: right;
  padding-right: 10px;
  color: #606266;
  font-weight: 500;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.total-amount {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.approval-info {
  margin: 30px 0;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

.el-form-item {
  margin-bottom: 22px;
}

::v-deep .el-input__inner {
  border-radius: 4px;
}

::v-deep .el-button {
  padding: 12px 20px;
  border-radius: 4px;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.el-dialog .el-table {
  margin-top: 20px;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>       this.pageSize = val
      this.loadBudgetList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadBudgetList()
    },
    loadBudgetList() {
      // 如果有搜索条件，进行过滤
      let filteredList = [...this.budgetList]
      
      if (this.searchQuery) {
        filteredList = filteredList.filter(item => 
          item.projectName.includes(this.searchQuery) ||
          item.department.includes(this.searchQuery)
        )
      }

      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0])
        const endDate = new Date(this.dateRange[1])
        filteredList = filteredList.filter(item => {
          const itemDate = new Date(item.startDate)
          return itemDate >= startDate && itemDate <= endDate
        })
      }

      // 更新总数和分页
      this.total = filteredList.length
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.budgetList = filteredList.slice(start, end)
    },
    getStatusType(status) {
      const map = {
        '待审批': 'warning',
        '已审批': 'success',
        '已驳回': 'danger'
      }
      return map[status] || 'info'
    },
    handleEdit(row) {
      // TODO: 实现编辑功能
      console.log('编辑', row)
    },
    handleDelete(row) {
      this.$confirm('确认删除该预算记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用删除API
        this.$message.success('删除成功')
        this.loadBudgetList()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.training-budget {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #f5f7fa;
}

.content {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
  font-weight: 600;
}

.budget-table {
  margin: 20px 0;
  border: 1px solid #ebeef5;
}

.budget-table ::v-deep .el-input__inner {
  text-align: center;
}

.budget-table ::v-deep .el-input-group__append {
  padding: 0 10px;
}

.subtotal, .per-fee {
  text-align: right;
  padding-right: 10px;
  color: #606266;
  font-weight: 500;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.total-amount {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.approval-info {
  margin: 30px 0;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

.el-form-item {
  margin-bottom: 22px;
}

::v-deep .el-input__inner {
  border-radius: 4px;
}

::v-deep .el-button {
  padding: 12px 20px;
  border-radius: 4px;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.el-dialog .el-table {
  margin-top: 20px;
}